//
//  MKButton.m
//  YYTextS
//
//  Created by Burn on 2019/9/11.
//  Copyright © 2019 menksoft. All rights reserved.
//

#import "MKButton.h"
#import <CoreText/CoreText.h>

@interface MKButton ()
{
    CGFloat imageH;
}
@property (nonatomic, strong) NSMutableAttributedString *attributedText;
@property(assign,nonatomic) NSInteger textRealLine;

@property(assign,nonatomic) CGFloat textWidth;
@property(assign,nonatomic) CGFloat textHeight;
@property(assign,nonatomic) CGFloat lineAscent;
@property(assign,nonatomic) CGFloat lineDescent;
@property(assign,nonatomic) CGFloat lineLeading;


@end

@implementation MKButton


- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
//        self.userInteractionEnabled = YES;
        UITapGestureRecognizer *labelTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clicked)];
        [self addGestureRecognizer:labelTapGestureRecognizer];
    }
    return self;
}


- (void)clicked{
    if (self.click) {
        self.click();
    }
}

- (void)drawRect:(CGRect)rect {
    
    //  绘制图
    imageH = self.image.size.height - (1 - (self.bounds.size.width - 10) / self.image.size.width) * self.image.size.height;
    [self.image drawInRect:CGRectMake(5, 5,self.bounds.size.width - 10,imageH)];
    
    
    
    
    [self updateAttributedText];    //  这里应该是设置字体和,字的方向
    //获取画布句柄
    CGContextRef context = UIGraphicsGetCurrentContext();
    //颠倒窗口 坐标计算使用的mac下的坐标系 跟ios的坐标系正好颠倒   下满三行代码主要就是颠倒  坐标好像是macOS来算的所以需要颠倒  注释三行代码就可以看到结果了
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    
    //生成富文本的信息 具体不懂  反正这是core text绘制的必须流程和对象
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)self.attributedText);
    //这一步生成合适的绘制区域
    CGPathRef path = [self createPathWithLines];
    
    // Create a frame for this column and draw it.
    CTFrameRef frame = CTFramesetterCreateFrame(framesetter,
                                                CFRangeMake(0, 0),
                                                path,
                                                (CFDictionaryRef)@{(id)kCTFrameProgressionAttributeName: @(kCTFrameProgressionLeftToRight)});
    CTFrameDraw(frame, context);
    
    //释放内存
    CFRelease(frame);
    CFRelease(path);
    CFRelease(framesetter);
}


-(void)updateAttributedText{
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:self.text attributes:nil];

    
    //为所有文本设置字体
    if (self.font) {
        CTFontRef fontRef = CTFontCreateWithName((CFStringRef)self.font.fontName, self.font.pointSize, NULL);
        // Set the lineSpacing.
        CGFloat lineSpacing = CTFontGetLeading(fontRef);
        // Create the paragraph style settings.
        CTParagraphStyleSetting setting;
        setting.spec = kCTParagraphStyleSpecifierLineSpacing;
        setting.valueSize = sizeof(CGFloat);
        setting.value = &lineSpacing;
        CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(&setting, 1);
        [attrStr addAttribute:(NSString *)kCTFontAttributeName
                        value:(__bridge id _Nonnull)(fontRef)
                        range:NSMakeRange(0, [attrStr length])];
        [attrStr addAttribute:(id)kCTParagraphStyleAttributeName
                        value:(__bridge id)paragraphStyle
                        range:NSMakeRange(0, [attrStr length])];
        CFRelease(fontRef);
        CFRelease(paragraphStyle);
    }
    
    if (self.textColor) {
        //设置颜色
        [attrStr addAttribute:(NSString *)kCTForegroundColorAttributeName
                        value:(__bridge id _Nonnull)(self.textColor.CGColor)
                        range:NSMakeRange(0,attrStr.length)];
    }
    
    self.attributedText = attrStr;
    [self caculateRealLine];
    [self setNeedsDisplay];
}


//计算富文本绘制真实产生的行数 以及文本显示的rect的宽高
-(void)caculateRealLine{
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)self.attributedText);
    CGMutablePathRef path = CGPathCreateMutable();//创建一个path句柄
    CGPathAddRect(path, NULL, CGRectMake(0,self.image.size.height * .7, self.bounds.size.width, self.bounds.size.height - self.image.size.height * .7));
    CTFrameRef frame = CTFramesetterCreateFrame(framesetter,
                                                CFRangeMake(0, 0),
                                                path,
                                                (CFDictionaryRef)@{(id)kCTFrameProgressionAttributeName: @(kCTFrameProgressionLeftToRight)});
    
    CFArrayRef lines = CTFrameGetLines(frame); //lines指向的指针是frame的属性 不能释放 否则释放frame时会过渡释放
    self.textRealLine = CFArrayGetCount(lines); //we should always set textRealLine before we user self.numberOfLines
    self.textHeight = 0;
    self.textWidth = 0;

    CTLineRef line = CFArrayGetValueAtIndex(lines, 0);
    CGFloat height = CTLineGetTypographicBounds(line, &_lineAscent, &_lineDescent, &_lineLeading);
    if (self.textHeight < height) {
        self.textHeight = height;
    }
        
    _textWidth = _textWidth + _lineDescent + _lineAscent + _lineLeading;
    
    CFRelease(frame);
    CFRelease(path);
    CFRelease(framesetter);
}


//  这一步生成合适的绘制区域 默认规则是居中
- (CGPathRef)createPathWithLines
{
    CGFloat y = (self.bounds.size.height - (self.image ? imageH : 0) - _textHeight - 5) * .5;
    CGRect contentRect = CGRectMake((self.bounds.size.width  - _textWidth) * .5,y, _textWidth, _textHeight);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, contentRect);
    return path;
}

@end
